import { FC, ReactElement, useEffect, useRef, useState } from 'react'
import {
  connect,
  Dispatch,
  OrganizationModelState,
  InstitutionListType
} from 'umi'
import type { ColumnsType } from 'antd/es/table'
import {
  Table,
  Card,
  Form,
  Button,
  Input,
  Modal,
  message,
  Select,
  Space
} from 'antd'
import type { FormInstance } from 'antd'
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import AddOrg from './components/add-organization'
import EditOrg from './components/edit-organization'
import styles from './index.less'
interface IProps {
  dispatch: Dispatch
  organizationModel: OrganizationModelState
}

// 索引签名，任意属性
interface FormValues {
  [name: string]: any
}
const { Option } = Select

const Organization: FC<IProps> = ({
  dispatch,
  organizationModel
}): ReactElement => {
  const formRef = useRef<FormInstance>(null)
  const { institutionList, gradeList } = organizationModel
  const [addShow, setAddShow] = useState<boolean>(false)
  const [editShow, setEditShow] = useState<boolean>(false)
  const [record, setRecord] = useState<InstitutionListType | undefined>(
    undefined
  )
  const [pageNum, setPageNum] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)

  const paginationProps = {
    current: pageNum, //当前页码
    pageSize, // 每页数据条数
    showTotal: () => <span>总共{total}项</span>,
    total, // 总条数
    onChange: (page: number, pageSize: number) =>
      handlePageChange(page, pageSize), //改变页码的函数
    hideOnSinglePage: false,
    showSizeChanger: false
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNum(page)
    setPageSize(pageSize)
  }

  // 删除机构
  const deleteOrganization = (code: string): void => {
    Modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除该学校吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'organizationModel/function_deleteSchoolInfo',
          payload: {
            code
          },
          callback: (response) => {
            if (response.code === 200) {
              message.success('删除成功')
              formRef.current?.submit()
            }
          }
        })
      }
    })
  }

  // 编辑机构
  const editUser = (record: InstitutionListType): void => {
    setRecord(record)
    setEditShow(true)
  }

  const columns: ColumnsType<InstitutionListType> = [
    {
      title: '序号',
      key: 'index',
      align: 'center',
      render: (_: string, record: InstitutionListType, index: number) => {
        return (
          <span>
            {((pageNum - 1) * pageSize + (index + 1))
              .toString()
              .padStart(2, '0')}
          </span>
        )
      }
    },
    {
      title: '所属学段',
      dataIndex: 'grade',
      key: 'grade',
      align: 'center'
    },
    {
      title: '学校名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '操作',
      render: (_: string, record: InstitutionListType) => {
        return (
          <Space size="large">
            <Button type="primary" onClick={() => editUser(record)}>
              修改
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => deleteOrganization(record.code)}
            >
              删除
            </Button>
          </Space>
        )
      },
      align: 'center'
    }
  ]

  const onFinish = (values: FormValues) => {
    getInstitutionList(values)
  }
  const resetForm = () => {
    formRef.current?.resetFields()
    setPageNum(1)
    setPageSize(10)
    getInstitutionList({})
  }

  // 查询学段
  const getGradeInfo = () => {
    dispatch({
      type: 'organizationModel/function_getGradeInfo',
      payload: {}
    })
  }

  // 获取机构列表
  const getInstitutionList = ({
    grade,
    name
  }: {
    grade?: string
    name?: string
  }) => {
    dispatch({
      type: 'organizationModel/function_getInstitutionList',
      payload: { grade, name }
    })
  }

  // 新增或修改成功刷新用户列表
  const handleUpdate = () => {
    formRef.current?.submit()
  }

  // 添加用户
  const addUser = () => {
    setAddShow(true)
  }

  useEffect(() => {
    getInstitutionList({})
    getGradeInfo()
  }, [])

  useEffect(() => {
    setTotal(institutionList.length)
    if (Math.ceil(institutionList.length / 10) < pageNum && pageNum > 1) {
      setPageNum((prev) => prev - 1)
    }
  }, [institutionList])

  return (
    <div className={styles.container}>
      <Card>
        <div className={styles['form-wrapper']}>
          <Form
            layout={'inline'}
            onFinish={onFinish}
            ref={formRef}
            initialValues={{ grade: '' }}
          >
            <Form.Item label="学段" name="grade">
              <Select placeholder="请选择参与学段" style={{ width: '200px' }}>
                <Option value="">全部</Option>
                {gradeList.map((item) => (
                  <Option value={item.dictKey} key={item.dictKey}>
                    {item.dictValue}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="学校名称" name="name">
              <Input placeholder="请输入学校名称" />
            </Form.Item>

            <Form.Item>
              <Space size="large">
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={resetForm}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
          <Button icon={<PlusOutlined />} onClick={addUser}>
            添加学校
          </Button>
        </div>

        <Table
          dataSource={institutionList}
          columns={columns}
          rowKey="code"
          pagination={paginationProps}
        />
      </Card>

      {/* 添加用户 */}
      <AddOrg
        visible={addShow}
        hide={() => {
          setAddShow(false)
        }}
        update={handleUpdate}
      />

      {/* 编辑用户 */}
      <EditOrg
        visible={editShow}
        hide={() => {
          setEditShow(false)
        }}
        record={record}
        update={handleUpdate}
      />
    </div>
  )
}

const mapStateToProps = ({
  organizationModel
}: {
  organizationModel: OrganizationModelState
}) => {
  return {
    organizationModel
  }
}
export default connect(mapStateToProps)(Organization)
